﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;
using MVVM.Demo.StockProvider;
using System.Windows;
using System.Windows.Threading;

namespace MVVM.Demo.Client
{
    public class WatchListViewModel : DependencyObject
    {
        private readonly IQuoteSource _source;
        private readonly Dispatcher _currentDispatcher;

        public ObservableCollection<Quote> Quotes { get; set; }

        public string Symbol { get; set; }



        public string LastSymbol
        {
            get { return (string)GetValue(LastSymbolProperty); }
            set { SetValue(LastSymbolProperty, value); }
        }

        // Using a DependencyProperty as the backing store for LastSymbol.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty LastSymbolProperty =
            DependencyProperty.Register("LastSymbol", typeof(string), typeof(WatchListViewModel), new UIPropertyMetadata(""));

        public WatchListViewModel(IQuoteSource source)
        {
            _currentDispatcher = Dispatcher.CurrentDispatcher;

            this.Quotes = new ObservableCollection<Quote>();

            _source = source;
            _source.QuoteArrived += new Action<Quote>(_source_QuoteArrived);
        }

        void _source_QuoteArrived(Quote quote)
        {
            Action dispatchAction = () => Quotes.Add(quote);
            _currentDispatcher.BeginInvoke(dispatchAction);
        }

        public void Subscribe()
        {
            _source.Subscribe(this.Symbol);
            this.LastSymbol = this.Symbol;
        }

    }
}
